import React, { useState, useEffect, useContext } from "react";
import { Link, useLocation } from "react-router-dom";
import { AppState } from "../App";
import "../css/songwarm.css";
import "../css/background.css";
import "../css/loader.css";

const SongWarm = () => {
  const App = useContext(AppState);
  const [Data, setData] = useState([]);
  const [num, setNum] = useState(0);
  const [Balance, setBalance] = useState("");
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const title = searchParams.get("tittle");
  const [loading, setLoading] = useState(true);

  const itemsPerPage = 3; 
  const [currentPage, setCurrentPage] = useState(1); 
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = Data.slice(indexOfFirstItem, indexOfLastItem);
  const pageNumbers = [];
  for (let i = 1; i <= Math.ceil(Data.length / itemsPerPage); i++) {
    pageNumbers.push(i);
  }

  const handleClick = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  const Vote = async (nums) => {
    try {
      const tx = await App.Foundationcontract.voteRequest(nums);
      await tx.wait();
      alert("投票成功");
      setNum(num + 1);
    } catch (error) {
      if (error.message === "YOu must be contributor") {
        alert("已投票");
      } else {
        console.log(error.message);
        alert("出了些问题");
      }
    }
  };

  const Donate = async (id) => {
    try {
      const tx = await App.Foundationcontract.executeRequest(id);
      await tx.wait();
      alert("捐赠成功！");
      setNum(num + 1);
    } catch (error) {
      if (error.message == "execution reverted: You already Voted") {
        alert("已投票");
      } else {
        console.log(error.message);
        alert("出了些问题");
      }
    }
  };

  useEffect(() => {
    const getBal = async () => {
      try {
        const Balance = await App.Foundationcontract.getBalance();
        setBalance(Balance);
      } catch (error) {
        console.log(error);
      }
    };
    getBal();
  }, [App.Foundationcontract]);

  useEffect(() => {
    if (App.Foundationcontract) {
      const getProposals = async () => {
        try {
          const Count = await App.Foundationcontract.requestsNumber();
          let proposals = [];
          for (let i = 0; i < Count; i++) {
            const Proposal = await App.Foundationcontract.requestions(i);
            console.log(Proposal.photo);
            if (Proposal.completed === false && Proposal.tittle === title) {
              proposals.push(Proposal);
            } else if (title === "") {
              proposals.push(Proposal);
            }
          }
          setData(proposals);
          setLoading(false); 
          console.log(proposals);
        } catch (error) {
          console.log(error);
        }
      };
      getProposals();
    }
  }, [App.Foundationcontract, num, title]);

  return (
    <div className="divFFF">
      {loading && <div className="loader"></div>} 
      <div className="container">
        <div className="blance">
          <h1>合约余额 - {Balance.toString()} WEI</h1>
        </div>

        <div class="grid sm:grid-cols-1 lg:grid-cols-3 gap-4">
          {currentItems.length !== 0 ? (
            currentItems.map((e, id) => {
              return (
                <div class="p-4">
                  <div class="h-full bg-gray-100 bg-opacity-75 px-8 pt-16 pb-24 rounded-lg overflow-hidden text-center relative dynamic-background">
                    <h2 class="tracking-widest -ml-5 text-15px title-font font-medium text-gray-900 mb-1">
                      筹款方地址
                    </h2>
                    <h2
                      class="tracking-widest -ml-5 text-base title-font font-medium text-gray-900 mb-1"
                      style={{ fontSize: "11px" }}
                    >
                      {e.recipient}
                    </h2>
                    <h2
                      class="tracking-widest -ml-5 text-base title-font font-medium text-gray-900 mb-1"
                      style={{ fontSize: "20px" }}
                    >
                      {e.tittle}
                    </h2>
                    <Link
                      to={`/header/songwarm/${e.uniqueid}`}
                      className="image-link"
                    >
                      <img
                        style={{ width: "300px", height: "300px" }}
                        src={`https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${e.photo}`}
                        alt="Proposal Photo"
                      />
                    </Link>
                    <h1 class="title-font sm:text-xl text-lg font-medium text-gray-900 mb-3"></h1>
                    <p class="leading-relaxed mt-5 mb-5">{e.description}</p>
                    <div class="text-center mt-2 leading-none flex justify-center absolute bottom-0 left-0 w-full py-4">
                      <span class="text-black  font-bold mr-3 inline-flex items-center leading-none text-sm pr-3 py-1 border-r-2 border-gray-200">
                        投票数
                      </span>
                      <span class="text-black font-bold  inline-flex items-center leading-none text-sm">
                        {e.votersNumber.toString()}
                      </span>
                      <span class="text-black ml-10 font-bold mr-3 inline-flex items-center leading-none text-sm pr-3 py-1 border-r-2 border-gray-200">
                        所需金额
                      </span>
                      <span class="text-black font-bold  inline-flex items-center leading-none text-sm">
                        {Number(e.targetMoney.toString())} WEI {}
                      </span>
                    </div>

                    <div className="flex justify-center absolute bottom-10 left-0 w-full py-4">
                      <button
                        onClick={() =>
                          Vote(Number(e.uniqueid.toString()))
                        }
                        class="flex mx-auto mt-10 text-white bg-yellow-400 border-0 py-2 px-8 focus:outline-none hover:bg-yellow-600 rounded"
                      >
                        投票
                      </button>
                      <button
                        onClick={() =>
                          Donate(Number(e.uniqueid.toString()))
                        }
                        class="flex mx-auto mt-10 text-white bg-yellow-400 border-0 py-2 px-8 focus:outline-none hover:bg-yellow-600 rounded"
                      >
                        捐赠
                      </button>
                    </div>
                  </div>
                </div>
              );
            })
          ) : (
            <div class="flex items-center justify-center nonDIv">
              <div class="title-font text-xl font-medium text-gray-900 mb-3 text-black">
                没有找到相关内容。
              </div>
            </div>
          )}
        </div>
        {currentItems.length !== 0 && (
        <div className="pagination-container">
          <button
            className={`pagination-button ${currentPage === 1 ? "disabled" : ""}`}
            onClick={() => handleClick(currentPage - 1)}
            disabled={currentPage === 1}
          >
            上一页
          </button>
          {pageNumbers.map((number) => (
            <button
              key={number}
              className={`pagination-button ${currentPage === number ? "active" : ""}`}
              onClick={() => handleClick(number)}
            >
              {number}
            </button>
          ))}
          <button
            className={`pagination-button ${currentPage === pageNumbers.length ? "disabled" : ""}`}
            onClick={() => handleClick(currentPage + 1)}
            disabled={currentPage === pageNumbers.length}
          >
            下一页
          </button>
        </div>
      )}
      </div>
    </div>
  );
};

export default SongWarm;
